package com.yl.ydk.presenter.impl

import android.content.Context
import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import com.yl.ydk.R
import com.yl.ydk.api.Api
import com.yl.ydk.base.BasePresenter
import com.yl.ydk.bean.GoodsListBean
import com.yl.ydk.presenter.contract.HealthyMallHomeContract
import com.yl.ydk.ui.activity.HealthyGoodsDetailActivity
import com.yl.ydk.ui.adapter.HealthyMallAdapter
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class HealthyMallHomeImpl : BasePresenter<HealthyMallHomeContract.View>(),
    HealthyMallHomeContract.Presenter<HealthyMallHomeContract.View> {


    var mallAdapter: HealthyMallAdapter? = null

    override fun getGoodsList(context: Context, vararg query: String?) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getGoodsList()
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<GoodsListBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: GoodsListBean?) {
                        dismissLoadingDialog()
                        if (t?.data != null && t.code == 200) {

                            mallAdapter = HealthyMallAdapter(t.data.list.toMutableList())
                            val manager = LinearLayoutManager(context)
                            manager.orientation = LinearLayoutManager.HORIZONTAL
                            mView?.getRecyclerView()?.let {
                                it.adapter = mallAdapter
                                it.layoutManager = manager
                            }
                            mallAdapter?.onListItemClick(object :
                                HealthyMallAdapter.onListItemClick {
                                override fun onListItemClick(item: GoodsListBean.DataX?) {
                                    mView?.getActivity()?.let {
                                        val intent =
                                            Intent(it, HealthyGoodsDetailActivity::class.java)
                                        intent.putExtra("data", item?.id)
                                        it.startActivityIn(intent, it)
                                    }
                                }
                            })
                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }


}